<template>
	<spin v-if="(!isLogin && loading) || !isReady" style="height: 200px;" />
	<router-view v-if="isLogin" />
</template>
<script lang="ts">
	import { computed, ComputedRef, defineComponent, onMounted, Ref, ref } from "vue";
	import { useStore } from "vuex";
	import { useRouter } from "vue-router";
	import Spin from '@/components/Spin/index.vue';
	import { useUserStore, User } from "@/store/user";


	interface SecurityLayoutSetupData {
		isLogin : ComputedRef<boolean>;
		loading : Ref<boolean>;
		getUser : () => Promise<void>;
		isReady : Ref<boolean>;
	}

	export default defineComponent({
		name: 'SecurityLayout',
		components: {
			Spin
		},
		setup() : SecurityLayoutSetupData {
			const router = useRouter();
			const store = useUserStore();

			// 获取当前登录用户信息
			const currentUser = computed<User>(() => store.$state.user);
			// 判断是否登录
			const isLogin = computed<boolean>(() => {
				return currentUser.value ? currentUser.value.id > 0 : false
			});
			// 读取当前用户信息func
			const isReady = ref<boolean>(false); // 是否读取过用户信息
			const loading = ref<boolean>(false);
			const getUser = async () => {
				loading.value = true;

				if (!isLogin.value && router.currentRoute.value.path !== '/login') {
					router.replace({
						path: '/login',
						query: {
							redirect: router.currentRoute.value.path,
							...router.currentRoute.value.query
						}
					})
				}
				loading.value = false;
				isReady.value = true;
			}

			onMounted(() => {
				getUser();
			})
			return {
				isLogin,
				loading,
				getUser,
				isReady
			}


		}
	})
</script>